package yunai.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

/**
 * @Author: DRevelation
 * @Date: 2021/6/30 17:47
 */
public class NioServer {

    private ServerSocketChannel serverSocketChannel;
    private Selector selector;

    public NioServer() throws IOException {
        // 打开
        serverSocketChannel = ServerSocketChannel.open();
        // 配置为非阻塞
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));

        selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("Server启动完成");

        hanldeKeys();
    }

    private void hanldeKeys() throws IOException {
        while (true) {
            // 通过Selector选择Channel
            int selectNums = selector.select(30 * 1000);
            if (selectNums == 0) {
                continue;
            }
            System.out.println("选择Channel数量：" + selectNums);

            //遍历可选择的Channel的SelectionKey集合
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                //移除下面要处理的
                iterator.remove();
                //忽略无效的
                if (!key.isValid()) {
                    continue;
                }
                hanldeKey(key);
            }
        }
    }

    private void hanldeKey(SelectionKey key) {
        if (key.isAcceptable()) {
            hanldeAcceptableKey(key);
        }
        if (key.isReadable()) {
            handleReadableKey(key);
        }
        if (key.isWritable()) {
            handleWritableKey(key);
        }
    }

    private void handleWritableKey(SelectionKey key) {

    }

    private void handleReadableKey(SelectionKey key) {
    }

    private void hanldeAcceptableKey(SelectionKey key) {
    }

    public static void main(String[] args) throws IOException {
        NioServer server = new NioServer();
    }

}
